package com.woniu.filter;

import com.alibaba.fastjson.JSON;


import com.woniu.outlet.dao.UserMapper;
import com.woniu.outlet.dao.WorkerMapper;
import com.woniu.outlet.po.User;
import com.woniu.outlet.po.UserExample;
import com.woniu.outlet.po.Worker;
import com.woniu.uitl.JwtTokenUitl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class GetPermsFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private WorkerMapper workerMapper;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String tokenStr = request.getHeader("tokenStr");
        log.info("token：" + tokenStr);
        String path = request.getRequestURI();
        log.info("请求路径1：" + path);
        if (request.getMethod().equals(HttpMethod.OPTIONS.toString())) {
            return;
        }
        //swagger放行
        if (path.contains("doc.html") || path.contains(".js") || path.contains(".css")
                || path.contains("swagger-resources") || path.contains("api-docs")
                || path.contains("v2") || path.contains("favicon.ico") || path.contains("login")) {
            filterChain.doFilter(request, response);
            return;
        }
        List<String> preCodes = new ArrayList<>();

        //获取用户名
        String account = JwtTokenUitl.getUserName(tokenStr);
        Worker worker = workerMapper.getWorkerByAccount(account);
        String keys = worker.getAccount() + worker.getPassword();

        //从Redis中获取对应权限
        String pros = redisTemplate.opsForValue().get(keys);
        if (!StringUtils.isEmpty(pros)) {
            preCodes = JSON.parseArray(pros, String.class);
            List<GrantedAuthority> authorities = new ArrayList<>();
            preCodes.forEach(preCode -> {
                authorities.add(new SimpleGrantedAuthority(preCode));
            });
            //将消息封装到认证对象中
            Authentication authen =
                    new UsernamePasswordAuthenticationToken(account, "", authorities);
            //存入security上下文中
            SecurityContextHolder.getContext().setAuthentication(authen);
            filterChain.doFilter(request, response);
        }else {
            preCodes = workerMapper.selectPercodeByPerm(account);
            List<GrantedAuthority> authorities = new ArrayList<>();
            preCodes.forEach(preCode -> {
                authorities.add(new SimpleGrantedAuthority(preCode));
            });
            //将消息封装到认证对象中
            Authentication authen =
                    new UsernamePasswordAuthenticationToken(account, "", authorities);
            //存入security上下文中
            SecurityContextHolder.getContext().setAuthentication(authen);
            //放行
            filterChain.doFilter(request, response);
        }
    }
}
